package com.yachang.qym.usbhost.fragment;

import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.NotificationCompat;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.squareup.leakcanary.RefWatcher;
import com.yachang.qym.usbhost.R;
import com.yachang.qym.usbhost.UsbApplication;
import com.yachang.qym.usbhost.activity.CallerActivity;
import com.yachang.qym.usbhost.model.RouteModel;
import com.yachang.qym.usbhost.utils.AllData;
import com.yachang.qym.usbhost.utils.NotifyIndex;
import com.yachang.qym.usbhost.utils.SendData;

import java.lang.reflect.Field;

/**
 * Created by qym on 2015/12/21.
 */
public class HomeFragment extends Fragment{

    private View mParentView;
    private TextView tvSendName;
    private TextView tvRouteName;
    private TextView tvRouteStyle;
    private TextView tvRouteOtherName;
    private TextView tvCalledName;
    private TextView tvNowArea;
//    private TextView tvNowPower;
    private RelativeLayout layoutCalled;
    private LinearLayout layoutChangeArea;
//    private LinearLayout layoutChangePower;

    private PopupWindow popupWindow;
    private int mRouteID;
    private RouteModel mRouteModel;
    public boolean thredCt = false;
    private Handler mHandler = new Handler(){
        public void handleMessage(Message msg){
            switch (msg.what) {
                case 0: {
                    bingData(mRouteID);
                }break;
                default:break;
            }
            super.handleMessage(msg);
        }
    };

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mParentView = inflater.inflate(R.layout.fragment_home, container, false);
        mRouteID = AllData.nowRoute;
        initView();
        if(mRouteID >= AllData.routeModels.size() || mRouteID < 0){
            Toast.makeText(getActivity(), "当前信道无数据，请切换信道!", Toast.LENGTH_SHORT).show();
        }else {
            bingData(mRouteID);
        }
        thredCt = true;
        GetNowRoute thread = new GetNowRoute();
        thread.start();

        return mParentView;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        thredCt = false;

        RefWatcher refWatcher = UsbApplication.getRefWatcher(getActivity());
        refWatcher.watch(this);
    }

    private void initView() {
        tvSendName = (TextView) mParentView.findViewById(R.id.tv_send_name);
        tvRouteName = (TextView) mParentView.findViewById(R.id.tv_now_route);
        tvRouteStyle = (TextView) mParentView.findViewById(R.id.tv_call_style);
        layoutCalled = (RelativeLayout) mParentView.findViewById(R.id.layout_called_list);
        tvRouteOtherName = (TextView) mParentView.findViewById(R.id.tv_route_other_name);
        tvCalledName = (TextView) mParentView.findViewById(R.id.tv_called_name);
        tvNowArea = (TextView) mParentView.findViewById(R.id.tv_now_area);
//        tvNowPower = (TextView) mParentView.findViewById(R.id.tv_now_power);
        layoutChangeArea = (LinearLayout) mParentView.findViewById(R.id.layout_more_area);
//        layoutChangePower = (LinearLayout) mParentView.findViewById(R.id.layout_more_power);

//        layoutChangePower.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                showPowerPopupWindow();
//            }
//        });
        layoutChangeArea.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showAreaPopupWindow();
            }
        });
        layoutCalled.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), CallerActivity.class);
                intent.putExtra("calledID", AllData.routeModels.get(mRouteID).getCalledsID());
                startActivity(intent);
            }
        });
    }

    private void bingData(int routeID) {
        if(routeID >= AllData.areaModels.get(AllData.machineInfo.getAreaID()).getRoutes().size() || routeID < 0){
            Toast.makeText(getActivity(), "当前信道数据错误！", Toast.LENGTH_SHORT).show();
            return;
        }
        tvNowArea.setText(AllData.areaModels.get(AllData.machineInfo.getAreaID()).getAreaId());
        mRouteModel = AllData.areaModels.get(AllData.machineInfo.getAreaID()).getRoutes().get(routeID);
        if(mRouteModel != null) {
            if(mRouteModel.getPower()){
//                tvNowPower.setText("高功率");
            }else {
//                tvNowPower.setText("低功率");
            }
            tvRouteName.setText(mRouteModel.getName());
            tvRouteOtherName.setText("DMR/CH" + (routeID + 1));
            if(mRouteModel.getCalledsID() - 1 < AllData.calledModels.size() && mRouteModel.getCalledsID() > 0)
                tvCalledName.setText(AllData.calledModels.get(mRouteModel.getCalledsID() - 1).getName());
            else
                Toast.makeText(getActivity(), "接收组列表为空！", Toast.LENGTH_SHORT).show();
            for (int i = 0; i < AllData.contactModels.size(); i++) {
                if (AllData.contactModels.get(i).getContactID() == mRouteModel.getCallerID()) {
                    tvSendName.setText(AllData.contactModels.get(i).getName());
                    SendData.data = SendData.sendNowRouteCaller(AllData.contactModels.get(i).getCallID());
                    SendData.needSend = true;
                    int callStyle = AllData.contactModels.get(i).getStyle();
                    switch (callStyle) {
                        case 0:
                            tvRouteStyle.setText("组呼");
                            break;
                        case 1:
                            tvRouteStyle.setText("个呼");
                            break;
                        case 2:
                            tvRouteStyle.setText("全呼");
                            break;
                    }
                    showNotification("当前信道：" + mRouteModel.getName());
                    break;
                }
            }
        }
    }

    private class GetNowRoute extends Thread{
        public void run(){
            while (thredCt) {
                if (AllData.nowRouteNeedChange) {
                    AllData.nowRouteNeedChange = false;
                    mRouteID = AllData.nowRoute;
                    Message message = new Message();
                    message.what = 0;
                    mHandler.sendMessage(message);
                }
            }
        }
    }

    private void showNotification(String info){
        NotificationCompat.Builder mBuilder =
                new NotificationCompat.Builder(getActivity())
                        .setSmallIcon(R.drawable.airport)
                        .setContentTitle(info)
                        .setContentText("信道号：" + "DMR/CH" + (mRouteID + 1));
        Resources res = getResources();
        Drawable drawable = res.getDrawable(R.mipmap.fire_icon);
        BitmapDrawable bitmapDrawable=(BitmapDrawable)drawable;
        Bitmap bitmap=bitmapDrawable.getBitmap();
        mBuilder.setLargeIcon(bitmap);
        Intent intent = new Intent(getActivity(), com.yachang.qym.usbhost.activity.MainActivity.class);
        intent.putExtra("index", 0);
        PendingIntent pendingIntent= PendingIntent.getActivity(getActivity(), 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        mBuilder.setContentIntent(pendingIntent);
        NotificationManager mNotificationManager =
                (NotificationManager) UsbApplication.getContext().getSystemService(Context.NOTIFICATION_SERVICE);
        mNotificationManager.notify(NotifyIndex.HOME_PAGE, mBuilder.build());
    }

    private void showPowerPopupWindow() {
        View contentView = LayoutInflater.from(getActivity()).inflate(
                R.layout.popup_parent, null);

        LinearLayout layoutParent = (LinearLayout) contentView.findViewById(R.id.layout_popup_parent);

        layoutParent.addView(createPowerView(true));
        layoutParent.addView(createPowerView(false));

        popupWindow = new PopupWindow(contentView,
                LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT, true);

        popupWindow.setTouchable(true);

        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        popupWindow.setTouchInterceptor(new View.OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return false;
            }
        });

        popupWindow.setAnimationStyle(R.style.PopupAnimation);
//        popupWindow.showAsDropDown(layoutChangePower);
        popupWindow.update();
    }


    private void showAreaPopupWindow() {

        View contentView = LayoutInflater.from(getActivity()).inflate(
                R.layout.popup_linear, null);

        LinearLayout layoutParent = (LinearLayout) contentView.findViewById(R.id.ll_list);

        for(int i = 0; i < AllData.areaModels.size(); i++){
            layoutParent.addView(createAreaView(i));
        }

        popupWindow = new PopupWindow(contentView,
                LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT, true);

        popupWindow.setTouchable(true);

        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        popupWindow.setTouchInterceptor(new View.OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return false;
            }
        });

        popupWindow.setAnimationStyle(R.style.PopupAnimation);
        popupWindow.showAsDropDown(layoutChangeArea);
        popupWindow.update();

    }

    private View createAreaView(final int count){
        View itemView = LayoutInflater.from(getActivity()).inflate(
                R.layout.popup_one_item, null);
        TextView mainText = (TextView) itemView.findViewById(R.id.tv_main_text);
        mainText.setText(AllData.areaModels.get(count).getAreaId());
        itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(count != AllData.machineInfo.getAreaID()) {
                    SendData.data = SendData.sendChangeArea().get(count);
                    SendData.needSend = true;
                    tvNowArea.setText(AllData.areaModels.get(count).getAreaId());
                    AllData.machineInfo.setAreaID(count);
                    bingData(mRouteID);
                }
                popupWindow.dismiss();
            }
        });
        return itemView;
    }

    private View createPowerView(boolean isWhat){
        View itemView = LayoutInflater.from(getActivity()).inflate(
                R.layout.popup_one_item, null);
        TextView mainText = (TextView) itemView.findViewById(R.id.tv_main_text);
        if(isWhat) {
            mainText.setText("高功率");
            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    SendData.data = SendData.sendHighPowerData();
                    SendData.needSend = true;
//                    tvNowPower.setText("高功率");
                    popupWindow.dismiss();
                }
            });
        }else {
            mainText.setText("低功率");
            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    SendData.data = SendData.sendLowPowerData();
                    SendData.needSend = true;
//                    tvNowPower.setText("低功率");
                    popupWindow.dismiss();
                }
            });
        }
        return itemView;
    }


    @Override
    public void onDetach() {
        super.onDetach();
        try {
            Field childFragmentManager = Fragment.class.getDeclaredField("mChildFragmentManager");
            childFragmentManager.setAccessible(true);
            childFragmentManager.set(this, null);
        } catch (NoSuchFieldException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }
}
